const coupon = require('../../templates/coupon/coupon');

Page({
  data: {
    tabIndex: 0,
    tabs: [
      {name: '待使用', state: 1, page: 1, noMore: false},
      {name: '已使用', state: 2, page: 1, noMore: false},
      {name: '过期券', state: 3, page: 1, noMore: false}
    ],
    couponList: []
  },
  onLoad: function () {
    this.getCoupons();
  },
  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },
  getCoupons: function () {
    let tabIndex = this.data.tabIndex,
        current = this.data.tabs[tabIndex];
    if (current.noMore) return;
    wx.util.request('user.coupon.my', {
      body: {
        page: current.page,
        state: current.state
      }
    }).then(coupons => {
      let list = this.data.couponList[tabIndex] || [];
      for (let item of coupons) {
        item = coupon.convert(item);
        list.push(item);
      }
      this.setData({
        [`couponList[${tabIndex}]`]: list,
        [`tabs[${tabIndex}].page`]: current.page + 1,
        [`tabs[${tabIndex}].noMore`]: coupons.length < 10
      });
    });
  },
  change: function (e) {
    let idx = e.detail.index,
        list = this.data.couponList[idx];
    this.setData({
      tabIndex: idx
    });
    if (!list || !list.length) {
      this.getCoupons();
    }
  },
  detail: function (e) {
    wx.navigateTo({
      url: `../coupon/detail?id=${e.currentTarget.dataset.id}`,
    })
  },
  more: function () {
    this.getCoupons();
  }
})